package com.xsir.ditan.miniprogram.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author user
 * @date 2021/1/28
 */
@Component
public class WeChatUtil {

    private static String appId;

    private static String secret;

    private static final String GRANT_TYPE = "authorization_code";

    private static final String BASE_URL = "https://api.weixin.qq.com/sns/jscode2session?";
    
    @Value("${wechat.appid}")
    public void setAppId(String wechatAppId) {
        appId = wechatAppId;
    }
    
    @Value("${wechat.secret}")
    public void setSecret(String wechatSecret) {
        secret = wechatSecret;
    }
    
    
    /**
     * 使用code换取session
     * @return
     */
    public static Map code2Session(String jsCode) {
        RestTemplate client = new RestTemplate();
    
        String url = BASE_URL + "appid=" + appId + "&" +
                "secret=" + secret + "&" +
                "grant_type=" + GRANT_TYPE + "&" +
                "js_code=" + jsCode;
        
        System.out.println("request url: " + url);
        
        ResponseEntity<String> entity = client.getForEntity(url, String.class);
        String body = entity.getBody();
    
        ObjectMapper objectMapper = new ObjectMapper();
        Map response = null;
        try {
            response = objectMapper.readValue(body, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    
        return response;
    }
    
}
